package com.meiyuetao.myt.md.service;

import java.util.List;

import lab.s2jh.core.dao.BaseDao;
import lab.s2jh.core.service.BaseService;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.meiyuetao.myt.md.dao.CommodityDao;
import com.meiyuetao.myt.md.dao.CommodityPresentDao;
import com.meiyuetao.myt.md.entity.Commodity;
import com.meiyuetao.myt.md.entity.CommodityPresent;

@Service
@Transactional
public class CommodityPresentService extends BaseService<CommodityPresent, Long> {

    @Autowired
    private CommodityPresentDao commodityPresentDao;

    @Autowired
    private CommodityDao commodityDao;

    @Override
    protected BaseDao<CommodityPresent, Long> getEntityDao() {
        return commodityPresentDao;
    }

    @Override
    public CommodityPresent save(CommodityPresent entity) {
        Commodity commodity = commodityDao.findOne(entity.getCommodity().getId());
        commodity.setNormalPresent(true);
        commodityDao.save(commodity);
        return super.save(entity);
    }

    @Override
    public void delete(CommodityPresent entity) {
        Commodity commodity = entity.getCommodity();
        super.delete(entity);
        List<CommodityPresent> commodityPresents = commodityPresentDao.findByCommodity(commodity);
        if (CollectionUtils.isEmpty(commodityPresents)) {
            commodity.setNormalPresent(false);
            commodityDao.save(commodity);
        }
    }
}
